var { Builder, By, until, Key } = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var firefox = require('selenium-webdriver/firefox');
var { readMDFile } = require('../markdown')
var axios = require('axios');
var path = require('path');
var fs = require('fs');

// var driver = new Builder()
//     .forBrowser('chrome')
//     // .setChromeOptions(new chrome.Options().headless())
//     .build();
// var driver = new Builder()
//     .forBrowser('MicrosoftEdge')
//     .build();
var driver = new Builder()
    .forBrowser('firefox')
    .setFirefoxService(new firefox.ServiceBuilder("./geckodriver.exe"))
    // .setFirefoxOptions(new firefox.Options().headless())
    .build();

// 
let mdPath = 'C:\\cuipengpeng\\code\\BComic\\README.md'
let url = 'https://juejin.cn/'
let mdUrl = 'https://juejin.cn/editor/drafts/new?v=2'
let domain = '.juejin.cn'
let httpOnlyCookies = ['n_mh', 'sessionid_ss', 'sessionid', 'sid_tt', 'uid_tt', 'uid_tt_ss', 'sid_guard', 'sid_ucp_v1', 'ssid_ucp_v1']
let secureCookies = ['sessionid_ss', 'uid_tt_ss', 'sid_ucp_v1', 'passport_csrf_token', 'ssid_ucp_v1']
// 
let contentXPath = '/html/body/div/div[2]/div/div/div/div[2]/div[1]/div/div[1]/textarea'
let titleXpath = '//*[@id="juejin-web-editor"]/div[2]/div/header/input'
let publishButtonXPath = '//*[@id="juejin-web-editor"]/div[2]/div/header/div[2]/div[2]/button'
let publishModalXPath = '/html/body/div/div[2]/div/header/div[2]/div[2]/div'
let tagXpath = '/html/body/div/div[2]/div/header/div[2]/div[2]/div/div[3]/div[2]/div/div/div/div[1]/input'
// let tagListXPath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[3]/div/div/div/span[1]/span'
let typeXpath = '/html/body/div[1]/div[2]/div/header/div[2]/div[2]/div/div[5]/div[2]/div/div/div/div[1]/input'
// let typeListXpath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[4]/div/div/div[2]/div[2]/div'
// let originalXpath = ''
let frontEndXpath = '//*[@id="juejin-web-editor"]/div[2]/div/header/div[2]/div[2]/div/div[2]/div[2]/div[2]'
let publishSubmitXpath = '/html/body/div[1]/div[2]/div/header/div[2]/div[2]/div/div[7]/div/button[2]'
let blogUrlXpath = '/html/body/div[1]/div/div/div[1]/main/div/div[2]/div/div[3]'
// 

/**
 * cookies 登录
 * @param {String} cookies 
 */
async function autoDeployBlog(cookies: string) {

    let array = cookies.split(';').map(_ => _.trim());
    // console.log('array :>> ', array.length);
    let object = {}
    array.forEach(item => {
        let keyValue = item.split('=')
        object[keyValue[0]] = keyValue[1]
    });
    // console.log('object :>> ', object);

    driver.get(url);

    await driver.manage().deleteAllCookies()

    for (let item in object) {
        if (item) {
            await driver.manage().addCookie({
                name: item,
                value: object[item],
                domain: domain,
                httpOnly: !!httpOnlyCookies.find(_ => _ == item),
                secure: !!secureCookies.find(_ => _ == item),
            });
        }
    }

    // 查看所有 Cookies
    // driver.manage().getCookies().then(function (cookies) {
    //     console.log('cookie details => ', cookies);
    // });

    // 打开写博客页面
    await driver.get(mdUrl)

    await driver.wait(until.elementLocated(By.xpath(contentXPath)))

    driver.findElement(By.xpath(contentXPath)).sendKeys(Key.CONTROL, 'a', Key.DELETE)
    driver.findElement(By.xpath(titleXpath)).sendKeys(Key.CONTROL, 'a', Key.DELETE)
    // 读取MD文件内容
    let { mdContent, mdTitle } = readMDFile(mdPath)
    // 标题，内容从文件里面取
    await driver.findElement(By.xpath(contentXPath)).sendKeys(mdContent)
    await driver.findElement(By.xpath(titleXpath)).sendKeys(mdTitle)
    // 进行发布文章配置
    await driver.sleep(2000)
    driver.findElement(By.xpath(publishButtonXPath)).click()
    await driver.wait(until.elementLocated(By.xpath(publishModalXPath)))
    // 添加标签
    await driver.findElement(By.xpath(tagXpath)).sendKeys('JavaScript', Key.ENTER)
    // 添加类型
    await driver.findElement(By.xpath(typeXpath)).sendKeys('JavaScript', Key.ENTER)
    // 添加分类
    await driver.findElement(By.xpath(frontEndXpath)).click()
    // 发布文章
    await driver.findElement(By.xpath(publishSubmitXpath)).click()
    // 得到地址
    let blogUrlEle = await driver.wait(until.elementLocated(By.xpath(blogUrlXpath)))
    blogUrlEle.click()
    let blogUrl =  await navigator.clipboard.readText()
    console.log('blogUrl :>> ', blogUrl);
}

// CSDN Cookies
// let cookies = 'uuid_tt_dd=10_19289789170-1591672702319-785094; dc_sid=c048c0187af82eb9ea1172f860527e59; UN=cuipp0509; Hm_ct_6bcd52f51e9b3dce32bec4a3997715ac=6525*1*10_19289789170-1591672702319-785094!5744*1*cuipp0509; c_segment=6; _ga=GA1.2.646447570.1597217438; __gads=ID=44bf219271797a71-22a79eebedc800a0:T=1621912694:RT=1621912694:S=ALNI_Ma0wVFECwcv2F4TdJTYcUuxDiOVNg; aliyun_webUmidToken=T2gAamfKoBgc-1TL0gmU28BmEafqLacJMzjjZp6vj4H070g4j5qv8r5x9wfIEoUJs-w=; p_uid=U010000; c_dl_prid=-; c_dl_rid=1636616487552_624122; c_dl_fref=https://blog.csdn.net/wf2397108372/article/details/96423251; c_dl_fpage=/download/weixin_38738830/16456995; c_dl_um=-; firstDie=1; dc_session_id=10_1637564968693.873675; c_page_id=default; SESSION=9ca5809f-c418-4f51-b12b-e4f938d74774; acw_sc__v2=619b47f75fe7ab62494cf488ca689f62587f06d3; c_first_ref=passport.gitcode.net; Hm_up_6bcd52f51e9b3dce32bec4a3997715ac={"uid_":{"value":"cuipp0509","scope":1},"islogin":{"value":"1","scope":1},"isonline":{"value":"0","scope":1},"isvip":{"value":"0","scope":1}}; log_Id_view=2346; c_pref=https://www.csdn.net/; c_ref=https://blog.csdn.net/cuipp0509; UserName=cuipp0509; UserInfo=d1121c010e0b4de99875d864399cbd73; UserToken=d1121c010e0b4de99875d864399cbd73; UserNick=喜欢路飞的银桑; AU=253; BT=1637568418682; log_Id_click=403; ssxmod_itna=QqAx07GQ0=DtqYve0d4YIEP7u7xfrLh70Aoh3O0dqGNLaDZDiqAPGhDC8+IA273h4NpF08BGQzKAhaq=eCEmg+TjQ7=ueDHxY=DU=GbwoD445GwD0eG+DD4DWDmmHDnxAQDjxGp9uXwV=Dm4GW8qGfDDoDYf6uDitD4qDBmhdDKqGg8TwG8TrUCntdEkDP60+9D0tQxBdN7cG9mjcH=GNPdZW8bGDDCoAz6DhzgjhPKmpuDB=pxBQljLNXjjHBldXxx43zvBveKkDFb0+PWD+KlOjde9wKlYx=FA4dYBGPKAhHRS5QQDDAeKKn0elGDD; ssxmod_itna2=QqAx07GQ0=DtqYve0d4YIEP7u7xfrLh70Aoh3O0qA6a4NYD/FKbDFEuu9wUoKAP49U6xBDkKjOOx0kod/MAPpQw+m8Tp3c7WMRUTV8ZOcwNgtzAPGTTfoxML87/Cvh7q87My6W/QLn8SiKzHOhN4r7kkPwTQSBHh2YGsroTdFemnEp5yayHSieTSoWro/AhQoPFLIOf2C8pz2pI=SPT2RemCE2Lg8MOujH7Q6GhC=YFV/dpYNQFZfBU2D2LoVpzxkQhKu5FaM1rFCwasc17tT7n7rt2PKC65ZqS27xG8B2M315Iy==ICoooETcMaTOz9Bx2YoYQbMhYxl3k3CqYtohedlO+Or=7=Yl+AOroiKsW=Oo7xgahqdzqpp+p7f3TLm+2bvmrVB8prwagGndp=mDLDDwpD=Ahc7hmnGPW3Ymew+nS=PISnmDh3fne4qkCD17xdlnEUcfgcDoq6fxYAvln5qDhmtpczmt7QdCxdDGcDG7z+edGs/0DCOo4D; c_first_page=https://editor.csdn.net/md/?not_checkout=1; dc_tos=r2yrw7; log_Id_pv=953; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1637560723,1637564970,1637566460,1637568441; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1637568441'
// 掘金 Cookies
let cookies = '_ga=GA1.2.1915245358.1606206963; MONITOR_WEB_ID=27e62e65-e7bd-4565-aae6-ef5131444555; passport_csrf_token_default=eb1e5344294aa01c0a1128cd633405c9; passport_csrf_token=eb1e5344294aa01c0a1128cd633405c9; sid_guard=3f72bb3be376f062f9e83728bc3378f2|1637650349|5184000|Sat,+22-Jan-2022+06:52:29+GMT; uid_tt=9463d9ada8665d92f23fb495a63c5ba2; uid_tt_ss=9463d9ada8665d92f23fb495a63c5ba2; sid_tt=3f72bb3be376f062f9e83728bc3378f2; sessionid=3f72bb3be376f062f9e83728bc3378f2; sessionid_ss=3f72bb3be376f062f9e83728bc3378f2; sid_ucp_v1=1.0.0-KDBjNmM1MDA3NGFjZjdhODBlOTc2N2QwMmEwYjlhNzE3YWM0OWIyNDYKFgj-_eDlq_XzBBCtn_KMBhiwFDgIQAsaAmxmIiAzZjcyYmIzYmUzNzZmMDYyZjllODM3MjhiYzMzNzhmMg; ssid_ucp_v1=1.0.0-KDBjNmM1MDA3NGFjZjdhODBlOTc2N2QwMmEwYjlhNzE3YWM0OWIyNDYKFgj-_eDlq_XzBBCtn_KMBhiwFDgIQAsaAmxmIiAzZjcyYmIzYmUzNzZmMDYyZjllODM3MjhiYzMzNzhmMg; n_mh=ekp69lUm7YLR9eOGUH5UPGU97CbzXvVzhDVv7bHmV_4';

autoDeployBlog(cookies)

